

<template>
    <view class="groupMembers" @touchmove="closeInput">
        <!-- <image
            class="psa"
            style="width:750rpx;height:834rpx;top:0;left:0;right:0;z-index:1;"
            src="../../static/bg1.jpg"
            mode=""
        ></image> -->
        <view
            style="
                background: #fff;
                width: 750rpx;
                position: fixed;
                z-index: 100;
            "
            :style="{ height: systemInfo.statusBarHeight + 'px' }"
        ></view>
        <view
            class="slim_header d-flex a-center j-center"
            style="border-bottom: none"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <view class="left_box" @tap="goBack">
                <image src="/static/center/back.png" class="back"></image>
            </view>
            <view class="title d-flex a-center j-between">发布动态</view>
            <view class="right_box">
            </view>
        </view>

        <scroll-view
            :scroll-y="true"
            class="content"
            @scroll="closeInput"
            :style="{ top: `calc(  100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="pingjia-input" @tap.stop="">
                <!-- <view class="title-header">
                    <text class="text">这一刻的想法</text>
                    <view class="back-info"></view>
                </view> -->
                <textarea
                    class="textar"
                    placeholder="请输入动态,不超过140字"
                    placeholderStyle="color:#ccc;"
                    :focus="isFocus"
                    @input="checkLength(280)"
                    @blur="isFocus=false;"
                    @focus="isFocus=true;"
                    v-model="contentText"
                ></textarea>


                <view class="images-list d-flex">
                    <view class="image-info" v-for="(item, index) in imgurlist" :id="`img${index}`" @tap.stop="previewImage(`img`,index,imgurlist)">
                        <image :src="item" class="touxiang" mode="aspectFill"></image>

                        <view class="shanchu d-flex a-center j-center">
							<image @tap="deleteImg(index)" class="image-del-icon" src="@/static/image/upload-image-del.png"></image>
						</view>


                        <!-- <view class="shanchu" @tap.stop="deleteImg(index)">
                            <image
                                src="../../static/rate/shanchu.png"
                                class=""
                            ></image>
                        </view> -->
                    </view>
                    <view
                        class="btns"
                        @click="choseImage"
                        v-if="imgurlist.length < 6"
                    >
                        <image
                            src="../../static/rate/paizhao.png"
                            class="paizhao"
                        ></image>
                    </view>
                </view>
            </view>

            <view class="auth d-flex a-center j-between" @tap="goTrendConfig">
                <text style="font-size:30rpx;">谁可以看</text>
                
                <view class="d-flex a-center">
                    <text style="color:#333;font-size:28rpx;">{{statusText}}</text>
                    <i class="icon row-icon icon-more-2"></i>
                </view>

            </view>

            <!-- <view class="pingjia-image">
                <view class="title-header">
                    <text class="text">上传照片</text>
                    <view class="back-info"></view>
                </view>
            </view> -->
        </scroll-view>


        <view class="btn_bottom_box">
            <view class="bottom_text d-flex a-center j-center">
                请勿发布非法信息和图片
            </view>
            <view
                class="btn_main_r"
                :class="{ disabled: !imgurlist.length && !contentText }"
                @tap="release"
            >
                <text class="text">发布</text>
            </view>
            <view class="bottom_seat"></view>
        </view>

    </view>

    <notice ref="noticePopup"></notice>
    <inputArea ref="input_area" :inputText="contentText" @updateText="updateText" @inpFocus="inpFocus" :keyboardHeight="keyboardHeight"></inputArea>
    <imagePreview ref="preview"></imagePreview>
</template>

<script setup lang="ts">
import { ref, computed, reactive,nextTick } from "vue";
import { onReady, onShow, onLoad,onUnload} from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { releaseTrend } from "@/api/api";
import cacheimg from "@/components/cacheimg.vue";
import { imStore as imStore1 } from "@/store/imStore";
import { wait, showLoading, closeLoading,replaceSwear } from "@/utils/utils";
import { BASE_URL } from "@/api/request";
import inputArea from "@/components/inputArea.vue";
import { getPosition } from "@/hooks/getPosition";
import { position as positionStore } from "@/store/position";
import imagePreview from "@/components/imagePreview.vue";
import { imageConvertArray,getHDImages } from "@/utils/format";
import { chooseImage } from "@/utils/utils";
import notice from "@/components/notice.vue";


const noticePopup = ref(null)


const position = positionStore();

const imStore: any = imStore1();

const goUserDetail = (userId: any) => {
    uni.navigateTo({
        url: `/pages/personalCenter/personalCenter?userId=${userId}`,
    });
};

const goTrendConfig = () => {
    uni.navigateTo({
        url: `/pages/trends/trendConfig?status=${status.value}`,
    });
};

const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const selected = ref([]);
const keyboardHeight = ref(0);
const input_area = ref(null)

const closeInput = ()=>{
    input_area.value.close();
}



const goBack = () => {
    uni.navigateBack();
};

const checkLength = (maxLength: number) => {
    let content = contentText.value.trim();
    let str = "";
    let len = 0;
    for (var i = 0; i < content.length; i++) {
        //正则表达式判断中文
        if (/[\u4e00-\u9fa5]/.test(content[i])) {
            len += 2;
        } else {
            len++;
        }

        if (len <= maxLength) {
            str += content[i];
        }
    }
    nextTick(() => {
        contentText.value = str;
    });
};

const imgurlist = ref([]);
const contentText = ref("");

const calcImageClass = computed(() => {
    if (imgurlist.value.length === 0 || imgurlist.value.length === 1) {
        return "l1";
    }
    if (imgurlist.value.length === 2) {
        return "l2";
    }
    if (imgurlist.value.length > 2) {
        return "l3";
    }
});

const choseImage = () => {
    chooseImage({
        success: (chooseImageRes) => {
            const token = uni.getStorageSync("api_token");
            const tempFilePaths = chooseImageRes.tempFilePaths;
            console.log("chooseImageRes");
            console.log(chooseImageRes);
            showLoading();
            uni.uploadFile({
                header: {
                    token,
                },
                url: `${BASE_URL}/file/upload`, //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: "file",
                formData: {
                    isCompress: 1,
                },
                success: (uploadFileRes) => {
                    let res: any;
                    closeLoading();
                    try {
                        res = JSON.parse(uploadFileRes.data);
                    } catch (error) {
                        uni.showToast({
                            icon: "none",
                            title: "请稍后再试",
                            duration: 1500,
                        });
                        return;
                    }

                    const { flag, data } = res;

                    if (flag !== 1) {
                        uni.showToast({
                            icon: "none",
                            title: "上传失败,请稍后再试",
                            duration: 1500,
                        });
                        return;
                    }

                    const { fileUrl } = data;
                    imgurlist.value.push(fileUrl);
                },
                fail() {
                    closeLoading();
                    uni.showToast({
                        icon: "none",
                        title: "上传失败,请稍后再试",
                        duration: 1500,
                    });
                },
            });
        },
    });
};

const deleteImg = (index: number) => {
    imgurlist.value.splice(index, 1);
};

let releaseLoading = false;

const status = ref(1);

const statusText = computed(()=>{
    if(status.value===1){
        return '公开、所有人可见...'
    }
    if(status.value===2){
        return '仅好友可见'
    }
    if(status.value===3){
        return '仅发布到附近动态'
    }
    if(status.value===4){
        return '仅自己可见'
    }
})

const release = async () => {

    const {latitude,longitude} = position;

    if(releaseLoading){
        return;
    }

    releaseLoading=true;

    showLoading();

    if (!contentText.value && !imgurlist.value.length) {
        uni.showToast({
            icon: "none",
            title: "请输入内容或上传图片",
            duration: 1500,
        });
        releaseLoading=false;
        closeLoading();
        return;
    }

    const params = {
        userId: userData.id,
        content: replaceSwear(contentText.value),
        picture: imgurlist.value.join(","),
        latitude,
        longitude,
        status:status.value,
    };

    const res = await releaseTrend(params);
    const {flag} = res;
    if(flag!==1){
        closeLoading();
        uni.showToast({
            icon: "none",
            title: "发布失败，请稍后再试",
            duration: 1500,
        });
        releaseLoading=false;
        return;
    }

    closeLoading();

    uni.showToast({
            icon: "success",
            title: "发布成功",
            duration: 1500,
    });

    setTimeout(()=>{
        goBack();
    },1500)
};

const updateText = (text:string)=>{
    contentText.value = text;
}


const onKeyboardHeightChange = (obj: any) => {
    const { height } = obj;
    keyboardHeight.value = height;
};

const isFocus = ref(false);

const inpFocus = ()=>{
    isFocus.value = true;
}


const preview = ref();
const previewImage = (idPre:string,index:number,urls:any) => {
	uni.createSelectorQuery().select(`#${idPre}${index}`).boundingClientRect().exec((ret) => {
		let params = {
            idPre,
			startInfo:[ret[0]],//图片的初始大小与位置
			index:index,//当前id
			urls:getHDImages(urls)//预览集合图片地址
		}
		preview.value.open(params);
	})
}

const statusChange = (num:number)=>{
    status.value = num;
}




onReady(() => {});

onLoad((option: any) => {
    getPosition(true,'发送动态需要使用位置信息');
    const pages = getCurrentPages();
    const currenturl = pages[pages.length - 1].route;
    const readed = uni.getStorageSync(`noticereaded-${currenturl}`)
    if(!readed){
        setTimeout(()=>{
            noticePopup.value.open();
        },500)
    }
     /* #ifndef H5 */
    uni.onKeyboardHeightChange(onKeyboardHeightChange);
    /*#endif*/

    uni.$on('statusChange',statusChange);
});

onUnload((option: any) => {

     /* #ifndef H5 */
    uni.offKeyboardHeightChange(onKeyboardHeightChange);
    /*#endif*/

    uni.$off('statusChange',statusChange);
});

onShow(() => {});
</script>

<style lang="scss" scoped>
.groupMembers {
    width: 750rpx;
    height: 100vh;
    background: #fff;
    overflow:hidden;
    overflow-y:hidden;

    .btn_main_r {
        /* #ifdef H5 */
        bottom:200rpx;
        /*#endif*/
        &.disabled {
            background: #ddd;
            .text {
                color: #999;
            }
        }
    }

    .content {
        position: absolute;
        width: 750rpx;
        left: 0;
        right: 0;
        // bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
        // bottom: calc(env(safe-area-inset-bottom) + 120rpx);
        bottom: 0;
        background: #f5f5f5;
        .nodata {
            flex-direction: column;
            align-items: center;
            justify-content: center;
            flex: 1;

            .img {
                width: 560rpx;
                height: 560rpx;
            }
            .desp {
                margin-top: 20rpx;
                width: 560rpx;
                .text {
                    font-size: 28rpx;
                    color: #999;
                }
            }
        }

        .pingjia-input {
            width: 710rpx;
            background: #ffffff;
            border-radius: 20rpx;
            margin: 20rpx auto;
            margin-bottom: 0;
            padding:20rpx;
            overflow:hidden;

            .title-header {
                font-size: 34rpx;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 600;
                color: #333333;
                padding: 20rpx 0 22rpx 30rpx;
                box-sizing: border-box;
                position: relative;
                .text {
                    position: relative;
                    z-index: 10;
                }

                .back-info {
                    width: 230rpx;
                    height: 26rpx;
                    background: linear-gradient(
                        270deg,
                        rgba(73, 243, 210, 0) 0%,
                        #23e2a6 100%
                    );
                    border-radius: 13rpx;
                    position: absolute;
                    left: 32rpx;
                    bottom: 25rpx;
                }
            }

            .textar {
                width: 670rpx;
                height: 300rpx;
                background: #f5f5f5;
                padding: 20rpx;
            }
        }

        .auth{
            width:710rpx;
            height:100rpx;
            background:#fff;
            border-radius: 10rpx;
            margin:0 auto;
            margin-top:30rpx;
            padding:0 20rpx;
            color:#999;
            font-size:30rpx;
            &:active{
                background:#f5f5f5;
            }
            
        }

        .pingjia-image {
            width: 710rpx;
            height: 550rpx;
            background: #ffffff;
            border-radius: 20rpx;
            margin: 20rpx auto;

            .title-header {
                font-size: 34rpx;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 600;
                color: #333333;
                padding: 20rpx 0 22rpx 30rpx;
                box-sizing: border-box;
                position: relative;
                .text {
                    position: relative;
                    z-index: 10;
                }

                .back-info {
                    width: 136rpx;
                    height: 26rpx;
                    background: linear-gradient(
                        270deg,
                        rgba(73, 243, 210, 0) 0%,
                        #23e2a6 100%
                    );
                    border-radius: 13rpx;
                    position: absolute;
                    left: 32rpx;
                    bottom: 25rpx;
                }
            }

        }

        .images-list {
                display: display;
                //grid-template-columns: repeat(3, 210rpx);
                width: 670rpx;
                gap:20rpx;
                margin-top:20rpx;
                flex-wrap: wrap;

                .btns {
                    width: 210rpx;
                    height: 210rpx;
                    border-radius: 4rpx;
                    border: 2rpx dashed #cccccc;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .paizhao {
                        width: 50rpx;
                        height: 50rpx;
                        border: 2rpx dashed #cccccc;
                    }
                }

                .image-info {
                    width: 210rpx;
                    height: 210rpx;
                    position: relative;
                    &.l1 {
                        width: 400rpx;
                        height: 400rpx;
                    }
                    &.l2 {
                        width: 280rpx;
                        height: 280rpx;
                    }
                    &.l3 {
                        width: 210rpx;
                        height: 210rpx;
                    }

                    .touxiang {
                        width: 100%;
                        height: 100%;
                        border-radius: 20rpx;
                    }

                    .shanchu {
                        position: absolute;
                        width: 40rpx;
                        height: 40rpx;
                        right: 10rpx;
                        bottom: 10rpx;
                        background: rgba(0,0,0,0.5);
                        border-radius: 50%;
                        .image-del-icon{
                            width: 32rpx;
                            height: 32rpx;
                        }
                    }
                }
            }
    }
}
.bottom_text {
    width: 750rpx;
    color: #999;
    font-size: 24rpx;
    margin-bottom:10rpx;
}
</style>
